package com.erp.erp_ui.base;

import com.danga.MemCached.MemCachedClient;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.utils.HttpSessionUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @ClassName Base
 * @Description 基类
 * @Author songjizhen
 * @Date 2020/6/19 11:17
 * @Version 1.0
 */
public class Base   {
    @Autowired
    protected MemCachedClient memCachedClient;


    /**
     * 将对象存入缓存
     * @param cacheName
     * @param obj
     * @return
     */
    protected boolean setBean(String cacheName,Object obj){
        return  memCachedClient.set(cacheName,obj);
    }

    /**
     * 从缓存中取出对象
     * @param cacheName
     * @return
     */
    protected Object getBean(String cacheName){
        if(cacheName.equals("user")){
            HttpSession session = HttpSessionUtils.get(this.getSession().getId());
            if (null==session){
                return null;
            }
            return session.getAttribute("user");
        }
        return memCachedClient.get(cacheName);
    }

    /**
     * 从缓存中移除一个对像
     * @return
     */
    protected boolean removeBean(String key){
        return memCachedClient.delete(key);
    }

    /**
     * 从会话缓存中删除一个会话
     * @param sessionid
     */
    protected  void removeSession(String sessionid){
         HttpSessionUtils.remove(sessionid);
    }

    /**
     * 获取当前会话
     * @return
     */
    protected HttpSession getSession() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        return request.getSession();
    }

    /**
     * 获取当前会话内容，即Request
     * @return
     */
    protected HttpServletRequest getRequest(){
        return  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
    }

    /**
     * 将对象设置到当前session中
     * @param key
     * @param obj
     * @return
     */
    protected void setObjectToSession(String key,Object obj){
        this.getSession().setAttribute(key, obj);
        HttpSessionUtils.set(this.getSession());

    }

    /**
     * 获取当前登陆者
     * @return
     */
    protected UserEntity getUser(){
        HttpSession session = HttpSessionUtils.get(this.getSession().getId());
        return (UserEntity)session.getAttribute("user");
    }


}
